package com.reeygu.item.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.reeygu.item.annotation.AccessLimit;
import com.reeygu.item.pojo.User;
import com.reeygu.item.service.UserService;
import com.reeygu.item.utils.CookieUtil;
import com.reeygu.item.vo.RespBean;
import com.reeygu.item.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

//该方法需要添加到mvc拦截器才能生效，跟resolvers一样
@Slf4j
@Component
public class AccessLimiInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //处理每个请求的时候他会进行拦截，下面通过判断是否有相关注解实现相应业务
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果拦截的是一个方法
        if (handler instanceof HandlerMethod) {
            User user = getUser(request, response);
            UserContext.setUser(user);
            if(user == null) {
                render(response, RespBeanEnum.SESSION_ERROR);
            }
            HandlerMethod hm = ((HandlerMethod) handler);
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);
            //没有这个注解则放行
            if (methodAnnotation == null) {
                return true;
            }
            int second = methodAnnotation.second();
            int maxCount = methodAnnotation.maxCount();
            boolean needLogin = methodAnnotation.needLogin();
            String key = request.getRequestURI();
            if (needLogin) {
                key += ":" + user.getId().toString();
            }
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if(count == null) {
                valueOperations.set(key, 0, second, TimeUnit.SECONDS);
            } else if(count < maxCount) {
                valueOperations.increment(key);
            } else {
                render(response, RespBeanEnum.VISIT_BUSY);
                return false;
            }
        }
        return true;
    }

    //构建放回对象
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(respBeanEnum);
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }

    //此处的方法原本在mvc参数解析器Resolvers里面的
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        log.info("拦截一条需要校验用户身份的信息userTicket:" + userTicket);
        return userService.getUserInfo(userTicket, request, response);
    }
}
